package top.z.template.parse.ast.expression;

import top.z.template.Context;
import top.z.template.Error;
import top.z.template.Template;
import top.z.template.parse.Ast.Expression;
import top.z.template.parse.Span;

import java.io.IOException;
import java.io.OutputStream;

/**
 * 三元操作, 等同于 Java 中的三元运算符
 */
public class TernaryOperation extends Expression {

    private final Expression condition; // 条件
    private final Expression positive;  // true
    private final Expression negative;  // false

    public TernaryOperation(Expression condition, Expression positive, Expression negative) {
        super(new Span(condition.getSpan(), negative.getSpan()));
        this.condition = condition;
        this.positive = positive;
        this.negative = negative;
    }

    public Expression getCondition() {
        return condition;
    }

    public Expression getNegative() {
        return negative;
    }

    public Expression getPositive() {
        return positive;
    }

    @Override
    public Object evaluate(Template template, Context context, OutputStream out) throws IOException {
        Object condition = getCondition().evaluate(template, context, out);
        if (condition instanceof Boolean) {
            if ((Boolean) condition) {
                return getPositive().evaluate(template, context, out);
            } else {
                return getNegative().evaluate(template, context, out);
            }
        }
        throw Error.error("Condition of ternary operator must be a boolean, got " + condition + ".", getSpan());
    }

}
